package 优先算法.模拟.数青蛙;

import java.util.HashMap;

/**
 *https://leetcode.cn/problems/minimum-number-of-frogs-croaking/description/
 */
public class Main {
    public static void main(String[] args) {
        Solution so = new Solution();
        String croakOfFrogs = "crcoakroak";
        int rel = so.minNumberOfFrogs(croakOfFrogs);
        System.out.println(rel);
    }
}
class Solution {
    public int minNumberOfFrogs(String croakOfFrogs) {
        if(croakOfFrogs.length() % 5 != 0) return -1;
        char[] in = {'c','r','o','a','k'};
        char[] croak = croakOfFrogs.toCharArray();
        HashMap<Character, Integer> index = new HashMap<>();
        HashMap<Character, Integer> map = new HashMap<>();
        int temp = 0;
        for(char c : in){
            index.put(c,temp);
            temp++;
        }
        int top = 0;
        while(top < croak.length){
            //先找到前一个字符
            char ch = croak[top];
            int priorIndex = ((index.get(ch)-1)+5)%5;//前一个字符的下表索引
            char priorCh =in[priorIndex];//获取前一个字符
            //判断是否存在哈希表中
            if(map.getOrDefault(priorCh,0)>0){
                //存在 前字符值减一 当前字符加一
                map.put(priorCh, map.getOrDefault(priorCh,0)-1);
                if(map.get(priorCh) < 0){
                    return -1;
                }
                map.put(ch, map.getOrDefault(ch,0)+1);
            }else{
                map.put(ch, map.getOrDefault(ch,0)+1);
            }
            top++;
        }
        //判断除了k之外的字符是否为0
        for(int i = 0;i < 3;i++){
            char ch = in[i];
            if(map.getOrDefault(ch,0) > 0){
                return -1;
            }
        }
        return map.getOrDefault(in[4],0);
    }
}
